

#include "musket.h"
#include "bullet.h"
#include "gamemanager.h"
#include "army.h"
#include "CCSkeletalSprite.h"
#include "gamescene.h"

#define __super         Unit

Musket::Musket() {

}

Musket::~Musket() {

}

void Musket::init(UnitInfo const& info, float unitScale) {
	__super::init(info, unitScale);
}

void Musket::update(float ticks) {
	__super::update(ticks);
}


void Musket::handleStateBirth(float ticks){
	transformState(UnitState::idle);
}

void Musket::handleStateDying(float ticks){
	if(sprite->animationIsDone()) {
		transformState(UnitState::died);
	}
}

void Musket::handleStateAim(float ticks){
	if(gameScene->battleState == BattleState::standby) {
		return;
	}

	if (_timeElapsed >= attribute.reloadTime) {
		if(gridInfo.globalLineIndex == ourArmy->frontLine && target) {
			transformState(UnitState::attack);
		} else {
			if(findDistantOpponent()) {
				transformState(UnitState::attack);
			}
		}
	}
}

void Musket::handleStateAttack(float ticks){
	if (sprite->animationIsDone()) {
		transformState(UnitState::aim);
	}
}

void Musket::handleStateIdle(float ticks){
	transformState(UnitState::reload);
}

void Musket::handleStateReload(float ticks){
	if (sprite->animationIsDone()) {
		transformState(UnitState::aim);
	}
}

void Musket::handleStateAssign(float ticks) {
	move(ticks);

	if(arrivedTargetPosition) {
		transformState(UnitState::aim);
	}
}

void Musket::handleStateWalk(float ticks){
	move(ticks);

	if(arrivedTargetPosition) {
		transformState(UnitState::aim);
	}
}

void Musket::handleStateWalkAim(float ticks){
	if(gameScene->battleState == BattleState::standby) {
		transformState(UnitState::aim);
	} else {
		move(ticks);

		if(arrivedTargetPosition) {
			transformState(UnitState::aim);
		} else if (_timeElapsed >= attribute.reloadTime) {
			if(findDistantOpponent()) {
				transformState(UnitState::walk_attack);
			}
		}
	}
}

void Musket::handleStateWalkAttack(float ticks){
	move(ticks);

	if (sprite->animationIsDone()) {
		if(arrivedTargetPosition) {
			transformState(UnitState::reload);
		} else {
			transformState(previousState);
		}
	}
}

void Musket::handleStateWalkReload(float ticks){
	move(ticks);

	if (sprite->animationIsDone()) {
		if(arrivedTargetPosition) {
			transformState(UnitState::aim);
		} else {
			transformState(UnitState::walk_aim);
		}
	}
}

void Musket::onAttack() {
	Unit* enemy = nullptr;
	if(gridInfo.globalLineIndex == ourArmy->frontLine) {
		enemy = target;
	} else {
		enemy = findDistantOpponent();
	}

	if(enemy) {
		auto from = sprite->getBonePositionRelativeToWorld("skeleton_head");
		auto to = enemy->sprite->getBonePositionRelativeToWorld("skeleton_head");
		to.y = from.y;
		Bullet* bullet = new Bullet(&attribute);
		bullet->init();
		enemy->addBullet(bullet);
	}

	_timeElapsed = 0;
}

void Musket::moveTo(const CCPoint &pos) {
	__super::moveTo(pos);

	transformState(UnitState::walk_aim);
}

void Musket::startAttack() {
}
